package online.longzipeng.mywebdemo.mq.consumer;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import com.rabbitmq.client.Channel;

import java.io.IOException;

/**
 * @Author: lzp
 * @description: 发布/订阅模式【广播】
 * 发布订阅模式（广播机制）（扇型交换机【此交换机直接广播所有消费者队列】），有交换机参与，每个消费者都有自己的队列，消息先经过交换机，由交换机决定送往哪个队列
 * @Date: 2024/1/14
 */
@Component
public class FanoutConsumer {

	//队列名称常量
	public static final String QUEUE_NAME1 = "fanout_queue1";
	public static final String QUEUE_NAME2 = "fanout_queue2";
	//交换机名称常量
	public static final String EXCHANGE_NAME = "fanout_exchange";

	/** ======================= 订阅模式， 广播，一个扇形交换机，两个消费队列 =========================*/

	/**
	 * 声明队列 Queue
	 */
	@Bean
	public Queue fanoutQueue1() {
		return new Queue(QUEUE_NAME1, true, false, false, null);
	}

	/**
	 * 声明队列 Queue
	 */
	@Bean
	public Queue fanoutQueue2() {
		return new Queue(QUEUE_NAME2, true, false, false, null);
	}


	/**
	 * 声明交换机
	 */
	@Bean
	FanoutExchange fanoutExchange() {
		return new FanoutExchange(EXCHANGE_NAME,true,false,null);
	}

	/**
	 * 交换机队列绑定
	 */
	@Bean
	Binding bindingFanoutExchange1(@Autowired Queue fanoutQueue1,@Autowired FanoutExchange fanoutExchange) {
		return BindingBuilder.bind(fanoutQueue1).to(fanoutExchange);
	}

	@Bean
	Binding bindingFanoutExchange2(@Autowired Queue fanoutQueue2,@Autowired FanoutExchange fanoutExchange) {
		return BindingBuilder.bind(fanoutQueue2).to(fanoutExchange);
	}



	/** 订阅模式， 广播，两个消费者 */
	@RabbitListener(queues = "fanout_queue1")
	public void receive1(String msgData, Message message, Channel channel) throws IOException {
		channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
		System.out.println("fanout_queue1消费者收到消息  : " +msgData);
	}

	@RabbitListener(queues = "fanout_queue2")
	public void receive2(String msgData, Message message, Channel channel) throws IOException {
		channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
		System.out.println("fanout_queue2消费者收到消息  : " +msgData);
	}

}
